﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using System.Linq.Dynamic.Core;
namespace Admin.NET.Application;

/// <summary>
/// SDK管理服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class IotsdkService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Iotsdk> _iotsdkRep;
    public IotsdkService(SqlSugarRepository<Iotsdk> iotsdkRep)
    {
        _iotsdkRep = iotsdkRep;
    }

    /// <summary>
    /// 分页查询SDK管理
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询SDK管理")]
    public async Task<SqlSugarPagedList<IotsdkOutput>> Page(PageIotsdkInput input)
    {
		input.SearchKey = input.SearchKey?.Trim();
        var query = _iotsdkRep.AsQueryable().Where(u => u.IsDelete == false)
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.ProgramLanguage.Contains(input.SearchKey)
                || u.SdkName.Contains(input.SearchKey)
                || u.SdkFileUrl.Contains(input.SearchKey)
                || u.Version.Contains(input.SearchKey)
                || u.SdkSign.Contains(input.SearchKey)
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.ProgramLanguage), u => u.ProgramLanguage.Contains(input.ProgramLanguage.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.SdkName), u => u.SdkName.Contains(input.SdkName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.SdkFileUrl), u => u.SdkFileUrl.Contains(input.SdkFileUrl.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Version), u => u.Version.Contains(input.Version.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.SdkSign), u => u.SdkSign.Contains(input.SdkSign.Trim()))
            //处理外键和TreeSelector相关字段的连接
            .Select((u) => new IotsdkOutput
            {
                Id = u.Id,
                ProgramLanguage = u.ProgramLanguage,
                SdkName = u.SdkName,
                SdkFileUrl = u.SdkFileUrl,
                Version = u.Version,
                SdkSign = u.SdkSign,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
            });
            //.Mapper(c => c.SdkNameAttachment, c => c.SdkName)
            //.Mapper(c => c.SdkFileUrlAttachment, c => c.SdkFileUrl)
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加SDK管理
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加SDK管理")]
    public async Task<long> Add(AddIotsdkInput input)
    {
        var entity = input.Adapt<Iotsdk>();
        await _iotsdkRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除SDK管理
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除SDK管理")]
    public async Task Delete(DeleteIotsdkInput input)
    {
        var entity = await _iotsdkRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _iotsdkRep.FakeDeleteAsync(entity);   //假删除
        //await _iotsdkRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新SDK管理
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新SDK管理")]
    public async Task Update(UpdateIotsdkInput input)
    {
        var entity = input.Adapt<Iotsdk>();
        await _iotsdkRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取SDK管理
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取SDK管理")]
    public async Task<Iotsdk> Detail([FromQuery] QueryByIdIotsdkInput input)
    {
        return await _iotsdkRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取SDK管理列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取SDK管理列表")]
    public async Task<List<IotsdkOutput>> List([FromQuery] PageIotsdkInput input)
    {
        return await _iotsdkRep.AsQueryable().Select<IotsdkOutput>().ToListAsync();
    }


    /// <summary>
    /// 上传SDK名称
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "UploadSdkName"), HttpPost]
    [DisplayName("上传SDK名称")]
    public async Task<SysFile> UploadSdkName([Required] IFormFile file)
    {
            var service = App.GetRequiredService<SysFileService>();
            return await service.UploadFile(new FileUploadInput { File = file, Path = "upload/SdkName" }); 
    }

    [ApiDescriptionSettings(Name = "GetDatabaseInfo"), HttpGet]
    [DisplayName("获取数据库信息")]
    public async Task<dynamic> GetDatabaseInfo()
    {
        var info = await _iotsdkRep.AsSugarClient().Ado.SqlQuery<dynamic>("show status").ToDynamicListAsync();
        return info;
    }
    /// <summary>
    /// 上传下载地址
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "UploadSdkFileUrl"), HttpPost]
    [DisplayName("上传下载地址")]
    public async Task<SysFile> UploadSdkFileUrl([Required] IFormFile file)
    {
            var service = App.GetRequiredService<SysFileService>();
            return await service.UploadFile(new FileUploadInput { File = file, Path = "upload/SdkFileUrl" }); 
    } 



}
